from model.class_model import Class
from database_connection.index import Session
from utils.utils import add_model

session = Session()


def add_one_class(class_info):
    try:
        category = add_model(class_info, "class")
        session.add(category)
    except Exception as e:
        session.rollback()
        return {"msg": "error"}
        # 将错误信息返回给前端
    else:
        session.commit()
        session.flush()
        session.refresh(category)
        return {"msg": "success", "data": category}


def find_one_class(class_info):
    # class_info需要查询的条件
    try:
        data = session.query(Class).filter_by(**class_info).first()
    except Exception as e:
        session.rollback()
        return {"msg": "error"}
    else:
        return {"msg": "success", "data": data}


def find_all_like_class(str_part):
    try:
        data = session.query(Class).filter(Class.class_label.like(f"%{str_part}%")).all()
    except Exception as e:
        session.rollback()
        return {"msg": "error"}
    else:
        return {"msg": "success", "data": data}


def find_all_class():
    try:
        data = session.query(Class).all()
    except Exception as e:
        session.rollback()
        return {"msg": "error"}
    else:
        return {"msg": "success", "data": data}


def find_num_of_blogs(class_id):
    try:
        data = session.query(Class).filter_by(id=class_id).first()
    except Exception as e:
        session.rollback()
        return {"msg": "error"}
    else:
        return {"msg": "success", "data": len(data.class_blog_list)}
